// 添加账号弹窗功能模块
// 支持的应用列表 - 移到全局作用域以便所有函数访问

const supportedApps = [
    { id: 'wechat', name: '微信公众号', icon: 'fa-weixin', color: '#07C160' },
    { id: 'douyin', name: '抖音', icon: 'fa-music', color: '#FE2C55' },
    { id: 'toutiao', name: '头条', icon: 'fa-newspaper-o', color: '#FF6A00' },
    { id: 'xiaohongshu', name: '小红书', icon: 'fa-bookmark', color: '#FE2C55' },
    { id: 'bilibili', name: '哔哩哔哩', icon: 'fa-play-circle', color: '#FB7299' },
    { id: 'kuaishou', name: '快手', icon: 'fa-video-camera', color: '#FE2C55' },
    { id: 'qq', name: 'QQ', icon: 'fa-qq', color: '#12B7F5' },
    { id: 'weibo', name: '微博', icon: 'fa-weibo', color: '#E6162D' },
    { id: 'netease', name: '网易', icon: 'fa-envelope', color: '#D71345' },
    { id: 'iqiyi', name: '爱奇艺', icon: 'fa-play', color: '#1677FF' },
    { id: 'youku', name: '优酷', icon: 'fa-play-circle-o', color: '#FF6700' },
    { id: 'baidu', name: '百度', icon: 'fa-search', color: '#2F80ED' }
];

function initAddAccountModal() {

    // 创建弹窗HTML结构
    const modalHtml = `
        <div id="addAccountModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden">
            <div class="bg-white rounded-lg shadow-lg w-full max-w-3xl max-h-[90vh] overflow-y-auto">
                <!-- 弹窗头部 -->
                <div class="flex justify-between items-center px-6 py-4 border-b border-gray-200">
                    <h3 class="text-xl font-semibold text-gray-800">添加账号</h3>
                    <button id="closeAddAccountModalBtn" class="text-gray-500 hover:text-gray-700 focus:outline-none">
                        <i class="fa fa-times text-lg"></i>
                    </button>
                </div>
                
                <!-- 弹窗内容 -->
                <div class="px-6 py-5">
                    <!-- 应用选择区域 -->
                    <div class="mb-6">
                        <h4 class="text-base font-medium text-gray-800 mb-3">选择应用</h4>
                        <div class="grid grid-cols-4 gap-4">
                            ${supportedApps.map(app => `
                                <div class="app-item flex flex-col items-center p-3 border border-gray-200 rounded-lg hover:border-primary hover:bg-primary/5 cursor-pointer transition-all" data-app-id="${app.id}" data-app-name="${app.name}">
                                    <div class="w-12 h-12 rounded-full mb-2 flex items-center justify-center" style="color: ${app.color};">
                                        <i class="fa ${app.icon} text-2xl"></i>
                                    </div>
                                    <span class="text-sm text-gray-700">${app.name}</span>
                                </div>
                            `).join('')}
                        </div>
                    </div>
                    
                    <!-- 授权说明 -->
                    <div class="bg-blue-50 rounded-lg p-4 mb-6">
                        <h4 class="text-base font-medium text-gray-800 mb-2">授权说明</h4>
                        <p class="text-sm text-gray-600 mb-2">点击上方应用图标，将跳转到对应应用的授权页面。</p>
                        <p class="text-sm text-gray-600">完成授权后，系统将自动保存您的授权信息，并在账号列表中显示。</p>
                    </div>
                    
                    <!-- 最近授权记录 -->
                    <div class="mb-6">
                        <h4 class="text-base font-medium text-gray-800 mb-3">最近授权</h4>
                        <div id="recentAuths" class="bg-gray-50 rounded-lg p-4 min-h-[100px]">
                            暂无最近授权记录
                        </div>
                    </div>
                </div>
                
                <!-- 弹窗底部 -->
                <div class="flex justify-end px-6 py-4 border-t border-gray-200">
                    <button id="cancelAddAccountBtn" class="px-4 py-2 border border-gray-300 rounded-md text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary">
                        取消
                    </button>
                </div>
            </div>
        </div>
    `;

    // 创建弹窗容器并插入HTML
    const modalContainer = document.getElementById('modalContainer');
    if (modalContainer) {
        modalContainer.innerHTML = modalHtml;
    }

    // 设置弹窗事件监听
    setupAddAccountModalEvents();
}

// 设置弹窗事件
function setupAddAccountModalEvents() {
    debugLog('设置弹窗事件绑定');

    const addAccountModal = document.getElementById('addAccountModal');
    const addAccountBtn = document.getElementById('addAccountBtn');
    const closeAddAccountModalBtn = document.getElementById('closeAddAccountModalBtn');
    const cancelAddAccountBtn = document.getElementById('cancelAddAccountBtn');

    // 检查关键DOM元素是否存在
    debugLog('检查DOM元素', {
        addAccountModal: !!addAccountModal,
        addAccountBtn: !!addAccountBtn,
        closeAddAccountModalBtn: !!closeAddAccountModalBtn,
        cancelAddAccountBtn: !!cancelAddAccountBtn
    });

    // 显示添加账号弹窗
    if (addAccountBtn && addAccountModal) {
        debugLog('添加addAccountBtn点击事件监听');
        addAccountBtn.addEventListener('click', function () {
            debugLog('addAccountBtn点击事件触发');
            addAccountModal.classList.remove('hidden');
            // 每次打开弹窗时重新初始化弹窗内容
            initModalContent();
            // 加载最近授权记录
            loadRecentAuths();
        });
    } else {
        debugLog('警告: addAccountBtn或addAccountModal未找到，无法绑定点击事件');
    }

    // 初始化弹窗内容为应用选择界面
    function initModalContent() {
        debugLog('初始化弹窗内容');
        const modalContent = addAccountModal.querySelector('.px-6.py-5');
        if (modalContent) {
            debugLog('找到modalContent元素，更新HTML');
            modalContent.innerHTML = `
                <!-- 应用选择区域 -->
                <div class="mb-6">
                    <h4 class="text-base font-medium text-gray-800 mb-3">选择应用</h4>
                    <div class="grid grid-cols-4 gap-4">
                        ${supportedApps.map(app => `
                            <div class="app-item flex flex-col items-center p-3 border border-gray-200 rounded-lg hover:border-primary hover:bg-primary/5 cursor-pointer transition-all" data-app-id="${app.id}" data-app-name="${app.name}">
                                <div class="w-12 h-12 rounded-full mb-2 flex items-center justify-center" style="color: ${app.color};">
                                    <i class="fa ${app.icon} text-2xl"></i>
                                </div>
                                <span class="text-sm text-gray-700">${app.name}</span>
                            </div>
                        `).join('')}
                    </div>
                </div>
                
                <!-- 授权说明 -->
                <div class="bg-blue-50 rounded-lg p-4 mb-6">
                    <h4 class="text-base font-medium text-gray-800 mb-2">授权说明</h4>
                    <p class="text-sm text-gray-600 mb-2">点击上方应用图标，将跳转到对应应用的授权页面。</p>
                    <p class="text-sm text-gray-600">完成授权后，系统将自动保存您的授权信息，并在账号列表中显示。</p>
                </div>
                
                <!-- 最近授权记录 -->
                <div class="mb-6">
                    <h4 class="text-base font-medium text-gray-800 mb-3">最近授权</h4>
                    <div id="recentAuths" class="bg-gray-50 rounded-lg p-4 min-h-[100px]">
                        暂无最近授权记录
                    </div>
                </div>
            `;

            // 重新绑定应用图标点击事件
            const appItems = document.querySelectorAll('.app-item');
            debugLog(`找到 ${appItems.length} 个应用图标项，准备绑定点击事件`);

            appItems.forEach(item => {
                item.addEventListener('click', function () {
                    const appId = this.getAttribute('data-app-id');
                    const appName = this.getAttribute('data-app-name');
                    debugLog(`应用图标点击事件触发: ${appName} (${appId})`);

                    // 对于微信公众号，显示专门的添加表单
                    if (appId === 'wechat') {
                        debugLog('调用showWechatAccountForm函数');
                        showWechatAccountForm();
                    } else {
                        // 显示授权确认对话框
                        if (confirm(`确定要授权 ${appName} 账号吗？点击确定后将跳转到授权页面。`)) {
                            // 模拟授权流程
                            simulateAuthorization(appId, appName);
                        }
                    }
                });
            });
        } else {
            debugLog('警告: modalContent元素未找到');
        }
    }

    // 关闭添加账号弹窗
    function closeAddAccountModal() {
        debugLog('关闭弹窗');
        if (addAccountModal) {
            addAccountModal.classList.add('hidden');
        }
    }

    // 点击关闭按钮
    if (closeAddAccountModalBtn) {
        debugLog('添加closeAddAccountModalBtn点击事件监听');
        closeAddAccountModalBtn.addEventListener('click', closeAddAccountModal);
    } else {
        debugLog('警告: closeAddAccountModalBtn未找到');
    }

    // 点击取消按钮
    if (cancelAddAccountBtn) {
        debugLog('添加cancelAddAccountBtn点击事件监听');
        cancelAddAccountBtn.addEventListener('click', closeAddAccountModal);
    } else {
        debugLog('警告: cancelAddAccountBtn未找到');
    }

    // 点击弹窗外部关闭弹窗
    if (addAccountModal) {
        debugLog('添加弹窗外部点击关闭事件监听');
        addAccountModal.addEventListener('click', function (e) {
            if (e.target === this) {
                closeAddAccountModal();
            }
        });
    }

    // 显示微信公众号添加表单
    function showWechatAccountForm() {
        debugLog('显示微信公众号添加表单');
        const modalContent = addAccountModal.querySelector('.px-6.py-5');
        if (modalContent) {
            debugLog('更新微信公众号表单HTML');
            modalContent.innerHTML = `
                <div class="mb-6">
                    <h4 class="text-xl font-medium text-gray-800 mb-4">添加公众号</h4>
                    
                    <div class="space-y-4">
                        <div>
                            <label for="wechatName" class="block text-sm font-medium text-gray-700 mb-1">公众号名称</label>
                            <input type="text" id="wechatName" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500" placeholder="请输入公众号名称">
                        </div>
                        
                        <div>
                            <label for="appId" class="block text-sm font-medium text-gray-700 mb-1">AppID</label>
                            <input type="text" id="appId" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500" placeholder="请输入公众号AppID">
                        </div>
                        
                        <div>
                            <label for="appSecret" class="block text-sm font-medium text-gray-700 mb-1">AppSecret</label>
                            <input type="text" id="appSecret" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500" placeholder="请输入公众号AppSecret">
                        </div>
                    </div>
                    
                    <div class="flex justify-center mt-6 space-x-4">
                        <button id="cancelWechatFormBtn" class="bg-gray-200 hover:bg-gray-300 text-gray-700 px-6 py-2 rounded-md transition-all">
                            取消
                        </button>
                        <button id="saveWechatAccountBtn" class="bg-green-500 hover:bg-green-600 text-white px-8 py-2 rounded-md transition-all flex items-center justify-center">
                            <i class="fa fa-save mr-2"></i>
                            保存公众号信息
                        </button>
                    </div>
                </div>
            `;

            // 添加取消按钮事件
            const cancelBtn = document.getElementById('cancelWechatFormBtn');
            if (cancelBtn) {
                debugLog('添加cancelWechatFormBtn点击事件监听');
                cancelBtn.addEventListener('click', function () {
                    debugLog('cancelWechatFormBtn点击事件触发');
                    // 返回到应用选择界面
                    initModalContent();
                    // 加载最近授权记录
                    loadRecentAuths();
                });
            } else {
                debugLog('警告: cancelWechatFormBtn未找到');
            }

            // 添加保存按钮事件
            const saveBtn = document.getElementById('saveWechatAccountBtn');
            if (saveBtn) {
                saveBtn.addEventListener('click', function () {
                    // 检查表单输入元素是否存在
                    const wechatNameInput = document.getElementById('wechatName');
                    const appIdInput = document.getElementById('appId');
                    const appSecretInput = document.getElementById('appSecret');

                    debugLog('检查表单输入元素', {
                        wechatNameInput: !!wechatNameInput,
                        appIdInput: !!appIdInput,
                        appSecretInput: !!appSecretInput
                    });

                    // 确保所有输入元素都存在
                    if (!wechatNameInput || !appIdInput || !appSecretInput) {
                        debugLog('错误: 表单输入元素未找到');
                        alert('表单初始化失败，请刷新页面重试');
                        return;
                    }

                    const wechatName = wechatNameInput.value;
                    const appId = appIdInput.value;
                    const appSecret = appSecretInput.value;

                    if (wechatName && appId && appSecret) {
                        // 发送请求保存数据
                        saveWechatAccountData(wechatName, appId, appSecret);
                    } else {
                        alert('请填写所有必填项！');
                    }
                });
            } else {
                debugLog('警告: saveWechatAccountBtn未找到，无法绑定点击事件');
            }
        } else {
            debugLog('警告: modalContent元素未找到');
        }
    }

    // 模拟授权流程
    function simulateAuthorization(appId, appName) {
        // 显示加载状态
        const loadingDiv = document.createElement('div');
        loadingDiv.className = 'fixed inset-0 bg-black bg-opacity-75 flex items-center justify-center z-50';
        loadingDiv.innerHTML = `
            <div class="bg-white p-6 rounded-lg text-center">
                <div class="fa fa-spinner fa-spin text-3xl text-primary mb-4"></div>
                <p class="text-lg text-gray-800 mb-2">正在准备${appName}授权...</p>
                <p class="text-sm text-gray-500">请稍候，即将跳转到${appName}授权页面</p>
            </div>
        `;
        document.body.appendChild(loadingDiv);

        // 模拟授权延迟
        setTimeout(() => {
            // 移除加载状态
            document.body.removeChild(loadingDiv);

            // 记录授权信息
            saveAuthRecord(appId, appName);

            // 关闭弹窗
            closeAddAccountModal();

            // 显示授权成功提示
            alert(`已跳转到${appName}授权页面，请在新页面完成授权操作。`);

            // 在实际应用中，这里应该跳转到对应的授权页面
            // window.location.href = `/authorize?app_id=${appId}`;
        }, 2000);
    }

    // 保存微信公众号数据到服务器
    function saveWechatAccountData(accountName, appId, appSecret) {
        debugLog('开始保存微信公众号数据', { accountName, appId, appSecretLength: appSecret ? appSecret.length : 0 });

        // 显示加载提示
        const saveBtn = document.getElementById('saveWechatAccountBtn');
        if (!saveBtn) {
            debugLog('错误: 保存按钮未找到');
            alert('保存功能初始化失败，请刷新页面重试');
            return;
        }

        const originalText = saveBtn.innerHTML;
        debugLog('保存按钮原始文本:', originalText);

        // 更新按钮状态
        saveBtn.disabled = true;
        saveBtn.innerHTML = '<i class="fa fa-spinner fa-spin mr-2"></i> 保存中...';
        debugLog('按钮状态已更新为禁用和加载状态');

        try {
            // 验证输入
            if (!accountName.trim() || !appId.trim() || !appSecret.trim()) {
                debugLog('输入验证失败：存在空值');
                throw new Error('请填写所有必填项');
            }

            // 准备账号关系数据
            const accountRelationData = {
                appId: appId.trim(),
                accountName: accountName.trim(),
                appType: 'wechat',
                appSecret: appSecret.trim(),
                icon: 'fa-weixin'  // 添加icon字段，保存微信公众号的图标
            };

            // 创建XMLHttpRequest对象，用于保存到user_account_relation表
            const xhrAccountRelation = new XMLHttpRequest();
            debugLog('创建XMLHttpRequest对象用于保存账号关系');
            xhrAccountRelation.open('POST', '/api/accounts/save', true);
            debugLog('设置请求方法和URL为/api/accounts/save');

            xhrAccountRelation.setRequestHeader('Content-Type', 'application/json');
            debugLog('设置请求头');

            // 添加详细的事件监听器
            xhrAccountRelation.onreadystatechange = function () {
                debugLog('账号关系保存请求状态变化:', {
                    readyState: xhrAccountRelation.readyState,
                    status: xhrAccountRelation.status
                });
            };

            xhrAccountRelation.onload = function () {
                // 恢复按钮状态
                saveBtn.disabled = false;
                saveBtn.innerHTML = originalText;

                try {
                    const relationData = JSON.parse(xhrAccountRelation.responseText);
                    debugLog('账号关系保存响应:', relationData);
                    
                    if (xhrAccountRelation.status === 200 && relationData.code === 0) {
                        alert('公众号信息保存成功！');
                        closeAddAccountModal();
                        // 保存成功后刷新账号列表
                        if (window.loadAccounts) {
                            window.loadAccounts();
                        } else {
                            // 如果loadAccounts函数不可用，刷新整个页面
                            location.reload();
                        }
                    } else {
                        alert('添加失败：' + (relationData.message || '服务器返回错误，状态码: ' + xhrAccountRelation.status));
                    }
                } catch (parseError) {
                    debugLog('解析响应出错:', parseError);
                    alert('添加失败：服务器返回格式错误的响应');
                }
            };

            xhrAccountRelation.onerror = function () {
                // 恢复按钮状态
                saveBtn.disabled = false;
                saveBtn.innerHTML = originalText;
                debugLog('账号关系保存请求失败');
                alert('保存公众号信息失败：网络错误，请检查连接');
            };

            xhrAccountRelation.ontimeout = function () {
                // 恢复按钮状态
                saveBtn.disabled = false;
                saveBtn.innerHTML = originalText;
                debugLog('账号关系保存请求超时');
                alert('保存公众号信息失败：请求超时');
            };

            xhrAccountRelation.timeout = 30000; // 30秒超时
            debugLog('设置超时为30秒');

            // 转换为JSON字符串
            const requestBody = JSON.stringify(accountRelationData);
            debugLog('请求体JSON字符串:', requestBody);

            debugLog('正在发送账号关系保存请求...');
            xhrAccountRelation.send(requestBody);
        } catch (error) {
            debugLog('保存过程中发生错误:', error);
            // 恢复按钮状态
            saveBtn.disabled = false;
            saveBtn.innerHTML = originalText;
            debugLog('按钮状态已恢复');
            alert('保存公众号信息失败：' + error.message);
        }
    }

    // 保存授权记录
    function saveAuthRecord(appId, appName) {
        // 从localStorage获取现有记录
        let recentAuths = JSON.parse(localStorage.getItem('recentAuths') || '[]');

        // 添加新记录
        const newRecord = {
            appId,
            appName,
            timestamp: new Date().toISOString()
        };

        // 确保不重复
        recentAuths = recentAuths.filter(record => record.appId !== appId);

        // 添加到开头
        recentAuths.unshift(newRecord);

        // 只保留最近5条
        if (recentAuths.length > 5) {
            recentAuths = recentAuths.slice(0, 5);
        }

        // 保存回localStorage
        localStorage.setItem('recentAuths', JSON.stringify(recentAuths));
    }

    // 加载最近授权记录
    function loadRecentAuths() {
        const recentAuths = JSON.parse(localStorage.getItem('recentAuths') || '[]');
        const recentAuthsContainer = document.getElementById('recentAuths');

        if (!recentAuths.length) {
            recentAuthsContainer.innerHTML = '暂无最近授权记录';
            return;
        }

        // 生成记录HTML
        const recordsHtml = recentAuths.map(record => {
            const date = new Date(record.timestamp);
            const formattedDate = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;

            return `
                <div class="flex items-center justify-between p-2 border-b border-gray-100 hover:bg-gray-50">
                    <div class="flex items-center">
                        <div class="w-8 h-8 rounded-full bg-primary/10 flex items-center justify-center mr-3">
                            <i class="fa fa-check text-primary"></i>
                        </div>
                        <span class="text-gray-800">${record.appName}</span>
                    </div>
                    <span class="text-xs text-gray-500">${formattedDate}</span>
                </div>
            `;
        }).join('');

        recentAuthsContainer.innerHTML = recordsHtml;
    }
}

// 添加全局错误监听，捕获所有JavaScript错误
window.addEventListener('error', function (event) {
    console.error('全局JavaScript错误:', event.error.message, '行号:', event.lineno);
});

// 调试函数 - 用于记录关键操作
function debugLog(message, data) {
    console.log(`[${new Date().toISOString()}] [AddAccount] ${message}`, data || '');
}

// 当DOM加载完成时初始化弹窗
debugLog('开始初始化添加账号模块');
if (document.readyState === 'loading') {
    debugLog('页面加载中，等待DOMContentLoaded');
    document.addEventListener('DOMContentLoaded', function () {
        debugLog('DOMContentLoaded事件触发，开始初始化弹窗');
        initAddAccountModal();
    });
} else {
    debugLog('页面已加载完成，直接初始化弹窗');
    // 页面已经加载完成，直接初始化
    initAddAccountModal();
}